﻿using Microsoft.Extensions.DependencyInjection;
using MiniCap.Abstractions;
using MiniCap.Core;
using MiniCap.Storage;
using MiniCap.Transport;
using MiniCap.Workers;

namespace MiniCap.Hosting
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddMiniCap(this IServiceCollection services,
            string mysqlHost, string mysqlUser, string mysqlPass,string mysqlDb, string rabbitHost, string rabbitUser, string rabbitPass, string virtualHost)
        {
            string mysqlConnStr = $"Server={mysqlHost};User ID={mysqlUser};Password={mysqlPass};Database={mysqlDb};";
            services.AddSingleton(_ => new MySqlOutboxStorage(mysqlConnStr, _.GetRequiredService<Microsoft.Extensions.Logging.ILogger<MySqlOutboxStorage>>()));

            services.AddSingleton(_ => new RabbitMqTransport(rabbitHost, rabbitUser, rabbitPass, virtualHost));

            services.AddSingleton<IMiniCapPublisher, MiniCapPublisher>();

            services.AddHostedService<OutboxDispatcherService>();
            services.AddHostedService<ConsumerService>();

            // 初始化数据库表
            var sp = services.BuildServiceProvider();
            var storage = sp.GetRequiredService<MySqlOutboxStorage>();
            storage.EnsureCreatedAsync().GetAwaiter().GetResult();

            return services;
        }
    }
}
